package ua.ck.example.web;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import ua.ck.example.domain.Customer;
import ua.ck.example.domain.Employee;
import ua.ck.example.domain.Provider;
import ua.ck.example.util.Constant;

public class AuthInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		String uri = request.getRequestURI();
		if (StringUtils.isEmpty(uri)) {
			return false;
		}

		// 不登陆也可以调的接口
		if (uri.contains("login") || uri.contains("register")
				|| uri.contains("product/index")) {
			return true;
		}
		if (request.getSession().getAttribute(Constant.SESSION_KEY_USER) != null) {
			return true;
		}
		PrintWriter printWriter = null;
		try {
			response.setStatus(HttpServletResponse.SC_FORBIDDEN);
			printWriter = response.getWriter();
			if (request.getSession().getAttribute(Constant.SESSION_KEY_USER) == null) {
				printWriter.write("会话已经过期了哦~请重新登陆了啦");
			}
		} catch (Exception e) {
		} finally {
			if (printWriter != null) {
				try {
					printWriter.flush();
					printWriter.close();
				} catch (Exception e1) {
				}
			}
		}
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		String type = (String) request.getSession().getAttribute(
				Constant.SESSION_KEY_USER_TYPE);
		if (type == null) {
			return;
		}
		if (type.equals(Constant.SESSION_PROVIDER_TYPE)) {
			modelAndView
					.addObject("userName", ((Provider) request.getSession()
							.getAttribute(Constant.SESSION_KEY_USER))
							.getProviderName());
		} else if (type.equals(Constant.SESSION_CUSTOMER_TYPE)) {
			modelAndView
					.addObject("userName", ((Customer) request.getSession()
							.getAttribute(Constant.SESSION_KEY_USER))
							.getCustomerName());
		} else if (type.equals(Constant.SESSION_EMPLOYEE_TYPE)) {
			modelAndView.addObject("userName", ((Employee) request.getSession()
					.getAttribute(Constant.SESSION_KEY_USER)).getEmpName());
		}

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
